#include "RenderTextureUtil.h"

RenderTextureUtil::RenderTextureUtil()
{
	_fbo = 0;
	glGenFramebuffers(1, &_fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, _fbo);

	_texWid = 256;
	_texHei = 256;

	glGenTextures(1, &_colortexture);
	glBindTexture(GL_TEXTURE_2D, _colortexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _texWid, _texHei, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glGenRenderbuffers(1, &_depthtexture);
	glBindRenderbuffer(GL_RENDERBUFFER, _depthtexture);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, _texWid, _texHei);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthtexture);
	glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _colortexture, 0);

	GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };// Set the list of draw buffers.
	glDrawBuffers(1, DrawBuffers);// define the draw buffers. this is not draw action itself. "1" is the size of DrawBuffers

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void RenderTextureUtil::render2texture(vector<RenderInterface*>& renderArray)
{
	
	glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
	glClearColor(0.f, 0.f, 0.f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);
	glViewport(0, 0, _texWid, _texHei);
	for (int i = 0; i < renderArray.size() ; ++i) {
		renderArray[i]->render();
	}
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	if (_debugNum==0) {
		_debugNum++;
		vector<unsigned char> tempdata(_texWid * _texHei*4);
		glBindTexture(GL_TEXTURE_2D, _colortexture);
		glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, tempdata.data());
		string tempname = string("texture_") + _debugName + ".raw";
		FILE* pf = fopen(tempname.c_str(), "wb");
		fwrite(tempdata.data(), 1, tempdata.size(), pf);
		fclose(pf);
		glBindTexture(GL_TEXTURE_2D, 0);
	}
}